﻿using CK.Sprite.Framework;
using System.Linq;
using System.Threading.Tasks;

namespace CK.Sprite.Form.Core
{
    public class FormItemHandler : AbstractSpriteViewHandler, ITransientDependency
    {
        public async Task<long> AddFormItem(FormItem formItem, GuidRepositoryBase<FormItem> formItemRepositoryParam = null)
        {
            var formItemRepository = formItemRepositoryParam == null ? new GuidRepositoryBase<FormItem>(DesignUnitOfWork) : formItemRepositoryParam;
            return await formItemRepository.InsertAsync(formItem);
        }

        public async Task<bool> UpdateFormItem(FormItem formItem, GuidRepositoryBase<FormItem> formItemRepositoryParam = null)
        {
            var formItemRepository = formItemRepositoryParam == null ? new GuidRepositoryBase<FormItem>(DesignUnitOfWork) : formItemRepositoryParam;
            return await formItemRepository.UpdateAsync(formItem);
        }

        public async Task DeleteFormItem(FormItem formItem, ISpriteCommonRepository spriteCommonRepository = null)
        {
            var formRows = await spriteCommonRepository.GetDatasById<FormRow>("FormRows", formItem.Id, "FormItemId");

            await spriteCommonRepository.DeleteById("FormItems", formItem.Id);
            await spriteCommonRepository.DeleteById("FormRows", formItem.Id, "FormItemId");
            if(formRows.Count > 0)
            {
                await spriteCommonRepository.DeleteByIds("FormCols", formRows.Select(r=>r.Id).ToList(), "FormRowId");
            }
        }
    }
}
